package cn.tanglong.basic.controller;

import cn.tanglong.basic.util.AjaxResult;
import cn.tanglong.basic.util.FastDfsUtil;
import org.apache.ibatis.annotations.Delete;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/fastdfs")
public class FastDfsController {

    /**
     * 上传接口
     * @param file
     * @return
     */
    @PostMapping
    public AjaxResult upload(@RequestPart(required = true,value = "file") MultipartFile file){
        try {
            // 获取图片后缀
            String filename = file.getOriginalFilename();// saljflsafj.slkdajflks.slkdfj.jpg
            String extName = filename.substring(filename.lastIndexOf(".") + 1);
            // 上传
            String path = FastDfsUtil.upload(file.getBytes(), extName); // /group1/lksadjf./sadf.jpg
            return AjaxResult.me().setResultObj(path);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMsg("系统错误");
        }
    }

    /**
     * 删除操作
     * @return
     *  localhost:8080/fastDfs/1
     */
    @DeleteMapping
    public AjaxResult delete(@RequestParam String path){  // /group1/asdfjsa/safsldf/sadfs.jpg
        try {
            String pathTmp = path.substring(1); // goup1/xxxxx/yyyy
            String groupName =  pathTmp.substring(0, pathTmp.indexOf("/")); //goup1
            String remotePath = pathTmp.substring(pathTmp.indexOf("/")+1);//
            FastDfsUtil.delete(groupName, remotePath);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMsg("系统错误");
        }
    }
}
